package miniProgram

import (
  "errors"
  "fmt"
  "gitee.com/yizhisamoye/GoWeChat/utils"
  "net/http"
  "strings"
  "time"
)

const BaseUrl = "https://api.weixin.qq.com"

type WxMiniProgram struct {
  appId       string
  appSecret   string
  accessToken string
  expireIn    int64
  expireTime  *time.Time
  Options     map[string]string
}

func NewWxMiniProgram(appId, appSecret string, options ...map[string]string) (*WxMiniProgram, error) {
  if strings.TrimSpace(appId) == "" || strings.TrimSpace(appSecret) == "" {
    return nil, errors.New("")
  }
  mp := new(WxMiniProgram)
  mp.appId = appId
  mp.appSecret = appSecret
  err := mp.FetchAccessToken()
  if len(options) > 0 {
     mp.Options = options[0]
  } else {
    mp.Options = make(map[string]string)
  }
  return mp, err
}

func (mp WxMiniProgram)FetchAccessToken()error{
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",mp.appId,mp.appSecret)
  resp, err := http.Get(url)
  if err != nil {
    return err
  }
  result, err := utils.CheckWxResp(resp)
  if err != nil {
    return err
  }
  if accessToken, exist := result["access_token"]; exist {
    mp.accessToken = accessToken.(string)
    mp.expireIn = int64(result["expires_in"].(float64))
    expireTime := time.Now()
    expireTime = expireTime.Add(time.Second * time.Duration(mp.expireIn))
    mp.expireTime = &expireTime
  }
  return nil
}

//验证access_token是否有效
func (c WxMiniProgram) IsAccessTokenValid() bool {
  if len(c.accessToken) == 0 {
    return false
  }
  if c.expireTime == nil {
    return false
  }
  if c.expireTime.Before(time.Now()) {
    fmt.Println(c.expireTime)
    return false
  }
  return true
}

//取出access_token,这里专门做成一个返回值的函数，忽略了拉去token的err，主要是为了方便直接使用
func(c *WxMiniProgram) GetAccessToken()string{
  if c.IsAccessTokenValid(){
    return c.accessToken
  }
  err:=c.FetchAccessToken()
  if err!=nil{
    return""
  }
  return c.accessToken
}

func(c *WxMiniProgram)GetAppId()string{
  return c.appId
}
